package jd;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class SimpleContainer {
    private Map<Class<?>, Object> beans = new HashMap<>();
    public void addBean(Class<?> beanClass) {
        try {
            Object instance = beanClass.getDeclaredConstructor().newInstance();
            beans.put(beanClass, instance);
            injectDependencies(instance);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public  void  injectDependencies(Object bean){
        Class<?> clazz = bean.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(Autowired.class)) {
                field.setAccessible(true);
                Class<?> Type = field.getType();
                Object bean1 = getBean(Type);
                try {
                    field.set(bean, bean1);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public <T> T getBean(Class<T> beanClass) {
        return (T) beans.get(beanClass);
    }
}
